<template>
  <ContentWrap v-loading="formLoading">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-row>
        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="参数模板名称" prop="parametersName">
            <el-input v-model="formData.parametersName" placeholder="请输入参数模板名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model="formData.sort"
              :min="0"
              placeholder="请输入排序"
              class="w-80!"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
          <template v-if="formData.parametersList.length == 0">
            <el-form-item label="商品参数">
              <el-button @click="addParameters">添加参数</el-button>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="商品参数">
              <el-table :data="formData.parametersList">
                <el-table-column align="center" label="参数名称" min-width="120">
                  <template #default="{ row }">
                    <el-input v-model="row.name" class="w-100%" />
                  </template>
                </el-table-column>
                <el-table-column align="center" label="参数值" min-width="240">
                  <template #default="{ row }">
                    <el-input v-model="row.value" class="w-100%" />
                  </template>
                </el-table-column>

                <el-table-column align="center" label="排序" min-width="168">
                  <template #default="{ row }">
                    <el-input-number
                      v-model="row.sort"
                      class="w-100%!"
                      :min="0"
                      placeholder="请输入排序"
                    />
                  </template>
                </el-table-column>
                <el-table-column align="center" label="操作" min-width="168">
                  <template #default="{ row }">
                    <el-button
                      class="ml-5px!"
                      type="primary"
                      link
                      @click.prevent="removeParameters(row)"
                    >
                      <Icon icon="ep:minus" :size="20" />
                    </el-button>
                    <el-button class="ml-5px!" type="primary" link @click.prevent="addParameters">
                      <Icon icon="ep:plus" :size="20" />
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
          </template>
        </el-col>
      </el-row>

      <el-form-item style="float: right">
        <el-button v-if="!isDetail" :loading="formLoading" type="primary" @click="submitForm">
          保存
        </el-button>
        <el-button @click="close">返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as ParametersApi from '@/api/mall/product/parameters'
import { FormRules } from 'element-plus'

defineOptions({ name: 'ProductParamentersAdd' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { params, name } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const isDetail = ref(false) // 是否查看详情

const otherRef = ref() // 其他设置 Ref
// SPU 表单数据
const formData = ref<ParametersApi.Parameters>({
  parametersId: undefined,
  parametersName: '', //商品名称
  sort: 0, // 商品排序
  parametersList: [] //参数列表
})
const formRules = reactive<FormRules>({
  parametersName: [{ required: true, message: '参数模版名称不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
/** 获得详情 */
const getDetail = async () => {
  const parametersId = params.parametersId as unknown as number
  if (parametersId) {
    formLoading.value = true
    try {
      const res = (await ParametersApi.getParameters(parametersId)) as ParametersApi.Parameters
      formData.value = res
    } finally {
      formLoading.value = false
    }
  }
}

/** 添加商品参数*/
const addParameters = () => {
  formData.value.parametersList.push({
    name: '', //参数名称
    value: '', //参数值
    sort: 0 //排序
  })
}
/** 删除商品参数*/
const removeParameters = (item) => {
  const index = formData.value.parametersList.indexOf(item)
  if (index !== -1) {
    formData.value.parametersList.splice(index, 1)
  }
}
/** 提交按钮 */
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    // 校验各表单

    await unref(formRef)?.validate()
    console.log(formData.value)
    // 深拷贝一份, 这样最终 server 端不满足，不需要影响原始数据
    const deepCopyFormData = cloneDeep(unref(formData.value)) as ParametersApi.Parameters

    // 校验都通过后提交表单
    const data = deepCopyFormData as ParametersApi.Parameters
    const parametersId = params.parametersId as unknown as number
    if (!parametersId) {
      await ParametersApi.createParameters(data)
      message.success(t('common.createSuccess'))
    } else {
      await ParametersApi.updateParameters(data)
      message.success(t('common.updateSuccess'))
    }
    close()
  } finally {
    formLoading.value = false
  }
}

/** 关闭按钮 */
const close = () => {
  delView(unref(currentRoute))
  push({ name: 'ProductParameters' })
}

/** 初始化 */
onMounted(async () => {
  await getDetail()
})
</script>
